package cn.pugle.base.thread.ticketlock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 使用Condition修复TicketLock3
 *
 * @author tzp
 * @since 2018/7/9
 */
public class TicketLock4 {
    private Map<Long, Condition> conditions = new HashMap<>();
    private Lock lock = new ReentrantLock();

    public void getLock(Long ticketNumber) {
        lock.lock();
        try {
            Condition condition = conditions.get(ticketNumber);
            while (condition != null) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                condition = conditions.get(ticketNumber);
            }
            conditions.put(ticketNumber, lock.newCondition());
        } finally {
            lock.unlock();
        }
    }

    public void removeLock(Long ticketNumber) {
        lock.lock();
        try {
            Condition condition = conditions.remove(ticketNumber);
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }
}

